/*
 * Copyright (c) 2025 Huawei Device, Inc. Ltd. and <马弓手>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ImagePicker.h"
#include "cJSON.h"
#include <filemanagement/file_uri/oh_file_uri.h>

REGISTER_PLUGIN_CLASS(ImagePicker)
bool ImagePicker::execute(const string&  action, cJSON* args, CallbackContext cbc)
{
    if(action == "getPictures") {
        m_cbc = cbc;
        cJSON* pJson = cJSON_GetArrayItem(args, 0);
        pJson = pJson->child;    
        int max = 20;
        do {
            if(pJson != NULL && pJson->string != NULL) {
                if(strcmp(pJson->string, "maximumImagesCount") == 0) {
                    max = pJson->valueint;
                }
                pJson = pJson->child;    
            }
        } while(pJson != NULL && pJson->string != NULL);
        char pPageArgs[5];
        sprintf(pPageArgs, "%d", max);
        return executeArkTs("./MediaAction/MediaAction/SelectMedia", 0, pPageArgs, "ImagePicker", cbc);
    }
    
    if(action == "hasReadPermission") {
        cbc.success();
    }
    
    if(action == "requestReadPermission")  {
        cbc.success();
    }
    
    if(action == "onArKTsResult") {
        return onArKTsResult(args);
    }
    return true;
}

bool ImagePicker::onArKTsResult(cJSON* args)
{
    cJSON* json = cJSON_GetObjectItem(args, "result");
    if(json != NULL && json->type == cJSON_Array) {
        cJSON* pArray = cJSON_CreateArray();
        int count = cJSON_GetArraySize(json);
        for(int i=0; i<count; i++) {
            cJSON* pJsonPath = cJSON_GetArrayItem(json, i);
            if(pJsonPath != nullptr && pJsonPath->type == cJSON_String) {
                string strPath = pJsonPath->valuestring;
                if(strPath.find("file://") == 0) {
                    char *pathResult = NULL;
                    FileManagement_ErrCode ret = OH_FileUri_GetPathFromUri(strPath.c_str(), strPath.length(), &pathResult);
                    if (ret == 0 && pathResult != NULL) {
                        cJSON* pStr = cJSON_CreateString(pathResult);
                        cJSON_AddItemToArray(pArray, pStr);
                        free(pathResult);
                        continue;
                    }
                }
                cJSON* pStr = cJSON_CreateString(strPath.c_str());
                cJSON_AddItemToArray(pArray, pStr);
            }
        }
        if(count > 0) {
            m_cbc.success(pArray);
        }
    }
    return true;
}